package com.cmy.common.utils;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @Author:Cmy
 * @Date:2023-03-28 9:39
 */
public class ResettableTimeTick<T> {

    public static volatile Thread thread;

    public volatile long lastTime;

    public volatile long countdown;

    private final Consumer<T> consumer;

    private T t;

    public ResettableTimeTick(Long countdown, TimeUnit timeUnit, Consumer<T> consumer, T t) {
        this.countdown = TimeUnit.SECONDS.toMillis(countdown);
        this.consumer = consumer;
        this.t = t;
    }

    public void tick(){
        //上一次
        //if (thread!=null){
        //    log.info("refresh lastTime");
        //}
        lastTime = System.currentTimeMillis();
        if (thread == null){
            synchronized (this){
                if (thread==null){
                    thread = new Thread(()->{
                        while (true){
                            //log.info("try to execute");
                            try {
                                long now = System.currentTimeMillis();
                                if (now>=lastTime+countdown){
                                    consumer.accept(t);
                                    break;
                                }
                                Thread.sleep((int)countdown/3);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        thread = null;//置空
                    });
                    thread.start();
                }
            }
        }
        //do nothing
    }

}

    